import React from 'react';
import {Link} from 'react-router-dom';
import '../../static/home/publicSentiment.styl'
import {Radio, message, Row, Col} from 'antd';
import axios from 'axios'
import Loading from '../common/Loading'
import {timestampToTime} from "../../util/util";
import $ from 'jquery'

const RadioGroup = Radio.Group;

const Pon = (props) => {
  let bg = ''
  let text = ''
  switch (props.positiveOrNegative) {
    case '1':
      bg = '#62c013'
      text = '正面'
      break
    case '2':
      bg = '#eb4a35'
      text = '负面'
      break
    default:
      bg = '#2184da'
      text = '中性'
  }
  let style = {
    display: 'inline-block',
    height: '8px',
    width: '8px',
    borderRadius: '50%',
    marginRight: '10px',
    background: bg
  }
  return <div>
    <span style={style}></span>
    <span>{text}</span>
  </div>
}
export default class PublicSentiment extends React.Component {
  state = {
    value: 2,
    visible: true,
    text: '负面',
    websiteData: [],
    docCount: [],
    sum: 0,
    num: 0,
    activeIndex: 0,
    modules: [],
    moduleDetails: [],
    details: [],
    loaded: false,
    docTotal: []
  };

  //positiveOrNegative change event
  onChange = (e) => {
    this.docCount(e.target.value)
    let pertext = '';
    if (e.target.value === 2) {
      pertext = '负面'
    } else if (e.target.value === 1) {
      pertext = '正面'
    } else if (e.target.value === 0) {
      pertext = '中性'
    }
    this.setState({
      value: e.target.value,
      text: pertext,
    });
  }

  //query websiteData
  queryTodayOpinion = async (e) => {
    let res = await
      axios.get('vrv-monitor-platform-web/data/queryTodayOpinion', {
        params: {
          aggsField: 'webSiteType',
          positiveOrNegative: -1
        }
      })
    if (res.data.statusCode === 200) {
      this.setState(prevState => ({
        websiteData: res.data.data,
        loaded: true
      }))
    } else {
      message.error(res.data.message)
    }
  }

  //count
  docCount = async (pon = -1) => {
    let res = await
      axios.get('vrv-monitor-platform-web/data/queryTodayOpinion', {
        params: {
          aggsField: 'positiveOrNegative',
          positiveOrNegative: pon
        }
      })
    if (res.data.data.length > 0) {
      if (pon === -1) {
        this.setState({
          docCount: res.data.data,
        }, () => {
          let sum = 0
          let i, j = this.state.docCount.length
          for (i = 0; i < j; i++) {
            if (this.state.docCount[i].key === 2) {
              this.setState({
                num: this.state.docCount[i].doc_count
              })
            }
            sum += Number(this.state.docCount[i].doc_count)
          }
          this.setState({
            sum: sum
          })
        })
      } else {
        this.setState({
          num: res.data.data[0].doc_count
        })
      }
    }
  }

  //positiveOrNegative change query moduleInfo
  addActive = async (id, bol) => {
    this.setState(prevState => ({
      modules: prevState.modules.map(item => {
        if (id === item.id) {
          item.latest = bol;
          item.data = null;
          item.docTotal = 0;
        }
        return item
      }),
    }))
    let res = await axios.get('vrv-monitor-platform-web/module/query', {
      params: {
        moduleId: id,
        positiveOrNegative: bol ? -1 : 2,
      }
    });
    if (res.data.statusCode === 200) {
      this.setState(prevState => ({
        modules: prevState.modules.map((item, index) => {
          if (item.id === id) {
            item.data = res.data.data
            item.docTotal = res.data.total
          }
          return item
        }),
      }))
    } else {
      message.error(res.data.message)
    }
  }

  //query modules
  queryTodayOpinion1 = async () => {
    let res = await
      axios.post('vrv-monitor-platform-web/module/queryByOrgCodeHome', {home: 1})
    if (res.data.statusCode === 200) {
      await this.setState({
        modules: res.data.data.map((item) => {
          item.latest = true
          return item
        })
      })
      this.make()
      this.queryModuleDetails()
    }
  }

  //获取模块具体信息
  queryModuleDetails = () => {
    this.state.modules.forEach((item, i) => {
      axios.get('vrv-monitor-platform-web/module/query', {
        params: {
          moduleId: item.id,
          positiveOrNegative: -1,
        }
      }).then(module => {
        this.setState(prevState => ({
          modules: prevState.modules.map(($item, index) => {
            if ($item.id === item.id) {
              $item.data = module.data.data
              $item.docTotal = module.data.total
            }
            return $item
          }),
        }))
      })
    })
  }

// 页面动画
  make = () => {
    let w = this.refs.publicSentiment.clientWidth
    let _this = this
    $.fn.gridup = function ({
                              width = (w - 20) / 2,
                              height = 362,
                              wgap = 20,
                              hgap = 20,
                              colnum = 2,
                              transition = 500,
                              data = []
                            } = {}) {
      let $el = this.eq(0)
      let $items = $el.children()
      let len = $items.length
      let $tmp
      let mdpos
      let mdflag = false
      let mz = 10
      let timer = {last: 0, curr: +new Date()}
      let getTopLeft = function ({col, row}) {
        return {
          left: col * (width + wgap),
          top: row * (height + hgap)
        }
      }
      $el.addClass('m-gridup')
      $el.css({
        width: colnum * (width + wgap) - wgap,
        height: Math.ceil(len / colnum) * (height + hgap) - hgap
      })
      let $bg = $('<div class="m-gridup-bg"></div>')
      $bg.css({width, height})
      $el.prepend($bg)
      console.log($items)
      if (data.length >= len) {
        $items.each((i, el) => $(el).data('d', data[i]))
      }
      $items.addClass('m-gridup-item')
      $items.css({
        width,
        height,
        transitionDuration: transition + 'ms'
      })
      $items.each(function (i, el) {
        let row = Math.floor(i / colnum)
        let col = i % colnum
        let $el = $(el)
        $el.css(getTopLeft({col, row}))
        $el.data('pos', {row, col})
      })
      $items.on('mousedown', function (e) {
        $tmp = $(this)
        let tmppos = $tmp.position()
        $bg.css(getTopLeft($tmp.data('pos')))
        mdpos = {
          x: e.pageX - tmppos.left,
          y: e.pageY - tmppos.top
        }
        $el.css('cursor', '-webkit-grab')
        $tmp.css('transition-duration', '0ms')
        $tmp.css('z-index', mz++)
        mdflag = true
      })
      $el.on('mousemove', function (e) {
        if (mdflag) {
          let offset = {
            top: e.pageY - mdpos.y,
            left: e.pageX - mdpos.x
          }
          $tmp.css(offset)
          timer.curr = +new Date()
          if (timer.curr - timer.last > 100) {
            timer.last = timer.curr
            $items.each(function (i, e) {
              let $e = $(e)
              let tpos = $tmp.data('pos')
              let epos = $e.data('pos')
              if (tpos.row === epos.row && tpos.col === epos.col) return
              let toff = getTopLeft(tpos)
              let eoff = getTopLeft(epos)
              let ch = height - Math.abs(eoff.top - offset.top)
              let cw = width - Math.abs(eoff.left - offset.left)
              if (ch > 0 && cw > 0 && ch * cw > width * height * 2 / 5) {
                $e.css(toff)
                $bg.css(eoff)
                $tmp.data('pos', epos)
                $e.data('pos', tpos)
              }
            })
          }
        }
      })
      $el.on('mouseup', function () {
        $el.css('cursor', '')
        mdflag = false
        let pos = getTopLeft($tmp.data('pos'))
        $tmp.css(pos)
        $tmp.css('transition-duration', transition + 'ms')
        if (JSON.stringify(arr) !== JSON.stringify(grid.getSorted())) {
          arr = grid.getSorted()
          _this.changeSeq(arr)
        }
      })
      return {
        getSorted() {
          return Array.from($items)
            .map(d => {
              let pos = $(d).data('pos')
              return {
                row: pos.row,
                col: pos.col,
                data: $(d).data('d')
              }
            }).sort((a, b) => a.row === b.row ? a.col - b.col : a.row - b.row)
            .map(d => {
              return d.data
            })
        }
      }
    }
    let modules = this.refs.modules
    let arr = this.state.modules.map(v => v.id)
    let grid = $(modules).gridup({
      data: arr
    })
  }

//拖拽排序
  changeSeq = (arr) => {
    axios.post('vrv-monitor-platform-web/module/changeSeq', {
      ids: arr.join(',')
    }).then(d => {
      console.log("排序操作成功")
    })
  }

//小数转换为百分比
  toPercent = (num) => {
    return (Math.round(num * 10000) / 100).toFixed(2) + '%';
  }

  createMarkup = (page) => {
    // this.keyLight(page,'再谈')
    let res = page.replace(/<br \/>/g, '').replace(/<br\/>/g, '').replace(/{{{/g, "<span class='light' style='color:red'>").replace(/}}}/g, "</span>")
    return {__html: res};
  };


  componentDidMount() {
    this.queryTodayOpinion()
    this.docCount()
    this.queryTodayOpinion1()
  }

  render() {
    let radioGroup = [{
      value: 2,
      text: '负面',
      color: 2 === this.state.value ? '#eb4a35' : '#9ba2ab'
    }, {
      value: 1,
      text: '正面',
    }, {
      value: 0,
      text: '中性',
    }]
    return (
      <div className="publicSentiment" ref="publicSentiment">
        <div className="m-title">今日舆情</div>
        <div className="statistics">
          <div className="items">
            <div className="total"><span>今日总量 :</span><span className="count">{this.state.sum}</span>
              <div className="total" style={{marginLeft: 30}}><span>{this.state.text}占比 :</span><span
                className="negative">{this.state.sum && this.toPercent(this.state.num / this.state.sum)}</span>
              </div>
            </div>
            <div className="clear-right">
              <RadioGroup onChange={this.onChange} value={this.state.value}>
                {
                  radioGroup.map((item, i) => {
                    return <Radio key={i} value={item.value} style={{color: `${item.color}`}}>{item.text}</Radio>
                  })
                }
              </RadioGroup>
            </div>
          </div>
          <div className="items">
            <div className="website">
              {
                this.state.websiteData.length > 0 ?
                  this.state.websiteData.map((item, index) => {
                    return <div key={index} className="item">
                      <div>{item.doc_count}</div>
                      <div>{item.websiteName}</div>
                    </div>
                  }) : <Loading/>
              }
            </div>
          </div>
        </div>
        <div className="list-box">
          <div className="modules m-gridup" ref="modules">
            {
              this.state.modules.map((module, i) => {
                return <div className="newsList" key={i}>
                  <div className="list-head">
                    <div className="list-title">{module.moduleName}（{module.docTotal})</div>
                    <div className="sortBy">
              <span className={module.latest ? 'active' : ''} onClick={() => {
                this.addActive(module.id, true)
              }}>最新</span>
                      <span className={!module.latest ? 'active' : ''} onClick={() => {
                        this.addActive(module.id, false)
                      }}>负面</span>
                      <img src={require('../../static/images/oval.png')} style={{verticalAlign: 'sub'}} alt="404"/>
                    </div>
                  </div>
                  <div className="list-bottom" style={{height: '320px', position: 'relative'}}>
                    {
                      module.data ?
                        <div>
                          <div style={{height: 280, overflow: 'hidden'}}>
                            {
                              module.data.length > 0 ?
                                module.data.map((item, index) => {
                                  return <div className="gutter-list" key={index}>
                                    <Row>
                                      <Col className="gutter-row" span={2}>
                                        <div className="gutter-box">
                                          <img className="img-icon"
                                               src='http://bmp.skxox.com/201710/01/qianxunqihua.104157.jpg' alt="404"/>
                                        </div>
                                      </Col>
                                      <Col className="gutter-row" span={10}>
                                        {/*<Linko to={'/detail?t='+Date.parse(new Date())+'&type='+(item.favoriteId?1:0)} target='_blank'>*/}
                                        {/*<div  className='titl' onClick={()=>this.detailset(item.id,item.titleContentPrint)} dangerouslySetInnerHTML={this.createMarkup(record.title.replace(/<br\/>/g, '').replace(/{{{/g,"<span class='light' style='color:red'>").replace(/}}}/g,"</span>"))}></div>*/}
                                        {/*</Linko>*/}
                                        <div className="gutter-box box">
                                          <Link
                                            to={'/detail?t=' + Date.parse(new Date()) + '&type=' + (item.favoriteId ? 1 : 0)}
                                            target='_blank'>
                                            <div title={item.title}
                                                 dangerouslySetInnerHTML={this.createMarkup(item.title.replace(/<br\/>/g, '').replace(/{{{/g, "<span class='light' style='color:red'>").replace(/}}}/g, "</span>"))}></div>
                                            <div title={item.content}
                                                 dangerouslySetInnerHTML={this.createMarkup(item.content.replace(/<br\/>/g, '').replace(/{{{/g, "<span class='light' style='color:red'>").replace(/}}}/g, "</span>"))}></div>
                                          </Link>
                                        </div>
                                      </Col>
                                      <Col className="gutter-row" span={3}>
                                        <div className="gutter-box"
                                             style={{textAlign: 'center', color: '#3c496a'}}>
                                          {<Pon positiveOrNegative={item.positiveOrNegative}/>}
                                        </div>
                                      </Col>
                                      <Col className="gutter-row" span={3}>
                                        <div className="gutter-box"
                                             style={{textAlign: 'center', color: '#3c496a'}}>{item.webSite}</div>
                                      </Col>
                                      <Col className="gutter-row" span={6}>
                                        <div className="gutter-box"
                                             style={{
                                               textAlign: 'center',
                                               color: '#3c496a'
                                             }}>{timestampToTime(item.addTime)}</div>
                                      </Col>
                                    </Row>
                                  </div>
                                }) : ''
                            }
                          </div>
                          {
                            module.data.length > 4 ? <div className="more">
                              <Link to={`/module/${module.id}`}>查看更多>></Link>
                            </div> : ''
                          }
                        </div> : <Loading/>
                    }
                  </div>
                </div>
              })
            }
          </div>
        </div>
      </div>
    );
  }
}